<style>
@import './assets/common.css';
</style>

<template>
  <router-view id="app" @login="loginDirect" @logout="logoutDirect"></router-view>
</template>

<script>
import Vue from 'vue';
import instance from './api';
import userPath from './router/fullpath';
import userPathDeal from './router/fullpathDeal';
import website from './router/website';
import statistics from './router/statistics';
import financeManage from './router/financeManage';
import capitalDetail from './router/capitalDetail';
import riskManage from './router/riskManage';
import systemSet from './router/systemSet';
import * as util from './assets/util.js';

// import infoData from './assets/info';

//请求拦截句柄
let myInterceptor;

export default {
  data() {
    return {
      menuData: null,
      menuDealData:null,
      userData: null
    }
  },
  methods: {
   
    setInterceptor: function(resourcePermission) {
      let vm = this;
      myInterceptor = instance.interceptors.request.use(function(config) {
        //得到请求路径
        let perName = config.url.replace(config.baseURL, '').replace('/GET','').replace('/POST','').split('?')[0];
        //权限格式1 /path/${param}
        let reg1 = perName.match(/^(\/[^\/]+\/)[^\/]+$/);
        if (reg1) {
          perName = reg1[1] + '**';
        }
        //权限格式2 /path/${param}/path
        let reg2 = perName.match(/^\/[^\/]+\/([^\/]+)\/[^\/]+$/);
        if (reg2) {
          perName = perName.replace(reg2[1], '*');
        }

        /*//校验权限
        if (!resourcePermission[config.method + ',' + perName]) {
          //调试信息
          console.warn(resourcePermission, config.method + ',' + perName);
          vm.$message({
            message: '无访问权限，请联系企业管理员',
            type: 'warning'
          });
          //拦截请求
          return Promise.reject({
            message: 'no permission'
          });
        }*/
        return config;
      });
    },
    getRoutes: function(userInfo) {
      if(!userInfo.menus){
        return console.warn(userInfo);
      }
      let vm = this;
      let allowedRouter = [];
      //将菜单数据转成多维数组格式
      let arrayMenus = util.buildMenu(userInfo.menus);
      //将多维数组转成对象格式
      let hashMenus = {};
      let setMenu2Hash = function(array, base,hm) {
        let hashKey='';
        array.map(key => {
          if (key.route) {
            if(hm!=undefined && hm!='undefined' && hm!=''){
            hashKey = ((base ? hm + '/' : '') + key.route).replace(/^\//, '');

            }else{
            hashKey = ((base ? base + '/' : '') + key.route).replace(/^\//, '');

            }
            hashMenus['/' + hashKey] = true;
            if (Array.isArray(key.children)) {
              setMenu2Hash(key.children, key.route, hashKey);
            }
          }
        });
      };
      setMenu2Hash(arrayMenus);
      //全局挂载hashMenus，用于实现路由守卫
      this.$root.hashMenus = hashMenus;
   
      //筛选本地路由方法
      let findLocalRoute = function(array, base,pk) {
        let replyResult = [];
        array.forEach(function(route) {
          let pathKey="";
          if(pk!=undefined&&pk!='undefined'&&pk!=''){
          pathKey = (base ? pk + '/' : '') + route.path;

          }else{
          pathKey = (base ? base + '/' : '') + route.path;

          }
          if (hashMenus[pathKey]) {
            if (Array.isArray(route.children)) {
              route.children = findLocalRoute(route.children, route.path,pathKey);
            }
            replyResult.push(route);
          }
        });
        if (base) {
          return replyResult;
        } else {
          allowedRouter = allowedRouter.concat(replyResult);
        }
      }

      let originPath = util.deepcopy(userPath[0].children);
    
      findLocalRoute(originPath);
      return allowedRouter;
    },
    extendRoutes: function(allowedRouter) {
      let vm = this;
    
      let originPath = util.deepcopy(allowedRouter);
      // originPath[0].children = actualRouter;
        vm.menuData = originPath;
        console.log(originPath)
/*      let originPathDeal = util.deepcopy(userPathDeal);
        vm.menuDealData = originPathDeal;
        vm.$router.addRoutes(originPathDeal);*/
      //注入路由
      vm.$router.addRoutes(originPath.concat([{
        path: '*',
        redirect: '/404'
      }]));
      console.log(vm.$router);
    },
    signin: function(callback) {
      let vm = this;
      //检查登录状态
 /*     let localUser = util.session('token');
      if (!localUser || !localUser.token) {
        return vm.$router.push({ path: '/login', query: { from: vm.$router.currentRoute.path } });
      }
      //设置请求头统一携带token
      instance.defaults.headers.common['Authorization'] = localUser.token;*/
      instance.defaults.headers.common['Authorization'] = "test";
      console.log("denglu")
        let userInfo=userPath[0];
        //取得资源权限对象
        // let resourcePermission = vm.getPermission(userInfo);
       /* let resourcePermission = vm.getPermission(localUser);*/
        //动态注入路由
        // vm.extendRoutes(allowedRouter);
        // let sessionMenus=JSON.parse(sessionStorage.getItem('routerPath'));

        console.log("test")
        let sessionMenusId=sessionStorage.getItem('routerPathId');
        if(sessionMenusId=="userPathDeal"){
            vm.extendRoutes(userPathDeal);     

        }else  if(sessionMenusId=="website"){
            vm.extendRoutes(website);     

        }else  if(sessionMenusId=="statistics"){
            vm.extendRoutes(statistics);     

        }else  if(sessionMenusId=="riskManage"){
            vm.extendRoutes(riskManage);     

        }else  if(sessionMenusId=="systemSet"){
            vm.extendRoutes(systemSet);     

        }else  if(sessionMenusId=="capitalDetail"){
            vm.extendRoutes(capitalDetail);     

        }else if(sessionMenusId=="financeManage"){
            vm.extendRoutes(financeManage);     

        }else{
           vm.extendRoutes(userPath);

        }
       /* if(sessionMenus){        
          vm.extendRoutes(sessionMenus);     

        }else{
          vm.extendRoutes(userPath);

        }*/
          // vm.extendRoutes(userPath);

        //保存数据用作他处，非必需
        // vm.menuData = allowedRouter;
       /* vm.userData = localUser;*/

        //权限检验方法
 /*       Vue.prototype.$_has = function(rArray) {
          let resources = [];
          let permission = true;

          if(!vm.allPermission( localUser.resourceList)){
              //提取权限数组
              if (Array.isArray(rArray)) {
                rArray.forEach(function(e) {
                  resources = resources.concat(e.p);
                });
              } else {
                resources = resources.concat(rArray.p);
              }
              //校验权限
              resources.forEach(function(p) {
                if (!resourcePermission[p]) {
                  if(vm.allPermissionUser(localUser.resourceList)){
                    return permission = true;

                  }else{
                    return permission = false;

                  }
                }
              });
          }          
          return permission;
        }*/
        //执行回调
        typeof callback === 'function' && callback();
      // })
    },
   getPermission: function(userInfo) {
      let resourcePermission = {};
      if (Array.isArray(userInfo.resourceList)) {
        userInfo.resourceList.forEach(function(e, i) {
          // let key = e.method.toLowerCase() + ',' + e.url;
          resourcePermission[e] = true;
        });
      }
      return resourcePermission;
    },
    allPermissionUser:function(resourceAll){//当登录用户用户用户管理所有权限
      let allowResouce=false;
      if(resourceAll!=null && resourceAll!="null" && resourceAll!=''&&resourceAll!=undefined&&resourceAll!="undefined"){
        resourceAll.map(x=>{           
            if(x.split(":")[1]=="permission"){
                return allowResouce=true;              
              }
          })
      }
       
       return allowResouce;
    },
    allPermission:function(resourceAll){//当登录用户有所有权限时
      let allowResouce=false;
      if(resourceAll!=null && resourceAll!="null" && resourceAll!=''&&resourceAll!=undefined&&resourceAll!="undefined"){
        resourceAll.map(x=>{
            if(x.split(":")[1]=="*"){
              return allowResouce=true;              
            }
      
          })
      }
       
       return allowResouce;
    },
    loginDirect: function(newPath){
      this.signin(() => {
        this.$router.replace({path: newPath || '/'});
      });
    },
    logoutDirect: function(){
      //清除session
      util.session('token','');
      //清除请求权限控制
      instance.interceptors.request.eject(myInterceptor);
      //清除菜单权限
      this.$root.hashMenus = {};
      //清除请求头token
      instance.defaults.headers.common['Authorization'] = '';
      //回到登录页
      this.$router.replace({path: '/login'});
    }
  },
  created: function(newPath) {
    this.signin();

  }
}
</script>